const express = require('express')
const router = express.Router()
const {logI} = require('../log.js')
const {retError, retSuccess} = require('../utils/ret')
const userDb = require('../db/user-db')
const checkType = require('../utils/checkType')
const checkToken = require('../utils/checkToken')
const checkDeviceNo = require('../utils/checkDeviceNo')
const moment = require('moment')

router
    .post('/', async(req, res) => {
        let {body: {maddr,token,buildingUUID,buildingName,companyName,address,city,introduction,deviceNo,isSelected}} = req
        logI('A-S', maddr, 'create_building', `${JSON.stringify(req.body)}`, 'null');
        try{
            const error = checkType.building(req.body)
            if(error){
                retError("create_building",maddr, 10001,  error.details[0].message, res);
            }else{
                let msg = {};
                msg = await checkToken(token,maddr);
                if(msg.code === 0){
                    const deviceInfo={
                        'maddr':maddr,
                        'deviceNo':deviceNo
                    }
                    let device={};
                    device = await checkDeviceNo(deviceInfo);
                    if(device.code === 0){
                        const time = moment().format('YYYY-MM-DD HH:mm:ss');
                        let ret = await userDb.updateBuilding(buildingUUID,buildingName,companyName,address,city,introduction,time,time,buildingName,buildingName,companyName,companyName,address,address,city,city,introduction,introduction,time);
                        if(ret === 1){
                            await userDb.insertBuildingMaddr(maddr,buildingUUID,time)
                        }
                        if(isSelected === 1){
                            await userDb.updateBuildingMaddr(buildingUUID,maddr)
                        }
                        const msgRet={
                            "createTime":time
                        }
                        retSuccess("create_building", maddr,0, msgRet, res);
                    }else{
                        retError("create_building", maddr,device.code, device.body, res);
                    }
                }else{
                    retError("create_building", maddr,msg.code, msg.body, res);
                }
            }
        } catch (e) {
            retError("create_building", maddr,10001, e, res);
        }

    })
module.exports = router
